package edu.usm.cs.roberge;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * Represents a news group message
 *
 */
public class Message implements Serializable {
	
	private static final long serialVersionUID = 1L;

	private NewsGroup newsGroup;
	private String messageNumber;
	private String messageId;
	private Map<String, String> headers;
	private String lastHeader;
	private String message;
	
	public Message(NewsGroup newsGroup) {
		this.newsGroup = newsGroup;
		headers = new HashMap<String, String>();
	}

	public void setMessageNumber(String string) {
		this.messageNumber = string;
	}

	public void setMessageId(String string) {
		this.messageId = string;
	}

	/**
	 * Append a header line to the message
	 * This method assumes the header lines will be appended
	 * in order they are returned from the news group server
	 * 
	 * @param headerText
	 */
	public void appendToHeader(String headerText) {
		int index = headerText.indexOf(':');
		
		// its possible for a header line to extend multiple
		// lines, in which case this method would be called twice
		// for the same header line.
		// if the line does not contain a ':', then it is assumed
		// to be an extension of the header line before it
		if (index < 0) {
			String lastHeaderVal = headers.get(lastHeader);
			headers.put(lastHeader, lastHeaderVal + headerText);
		} else {
			String headerName = headerText.substring(0, index);
			String value = headerText.substring(index + 1).trim();
			headers.put(headerName, value);
			lastHeader = headerName;
		}
	}

	public String getMessageId() {
		return messageId;
	}
	
	public NewsGroup getNewsGroup() {
		return newsGroup;
	}

	@Override
	public String toString() {
		return "message number: " + messageNumber + " messageHeaders: " + headers.toString();
	}

	public void appendToBody(String bodyText) {
		if (message == null) {
			message = bodyText;
		} else {
			message += "\n" + bodyText;
		}
	}

	public boolean hasBody() {
		return message != null;
	}

	public String getBody() {
		return message;
	}

	public String getSubjectHeader() {
		if (headers.containsKey("Subject")) {
			return headers.get("Subject");
		}
		
		return "No Subject for this message";
	}
}
